#coding=utf-8
#此程序为先利用PhantomJS进行登录操作，获取到headers和cookies
from selenium import webdriver
import json
from collections import OrderedDict
import time
from selenium.webdriver.chrome.options import Options

def getResponseHeaders(browser):
    har = json.loads(browser.get_log('har')[0]['message'])
    return OrderedDict(sorted([(header["name"], header["value"]) for header in har['log']['entries'][0]['response']["headers"]], key = lambda x: x[0]))

def getResponseStatus(browser):
    har = json.loads(browser.get_log('har')[0]['message'])
    return (har['log']['entries'][0]['response']["status"],str(har['log']['entries'][0]['response']["statusText"]))




#获取headers+cookies
def login_headers(url,keywords,password):
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.delete_all_cookies()
    driver.get(url+"/user/login/")
    driver.find_element_by_id("keywords").send_keys(keywords)
    driver.find_element_by_id("password").send_keys(password)
    driver.find_element_by_id("login_button").click()
    time.sleep(2)
    driver.refresh()
    # 获取与组合保存cookie
    # 获取cookie列表
    cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    cookiestr = cookiestr.encode('utf-8')
    cookies = dict([l.split("=", 1) for l in cookiestr.split("; ")])
    print cookies
    return cookies


# 获取cookies
def login_cookies(url,keywords,password):
    driver = webdriver.PhantomJS()
    driver.delete_all_cookies()
    driver.get(url+"/user/login/")
    driver.find_element_by_id("keywords").send_keys(keywords)
    driver.find_element_by_id("password").send_keys(password)
    driver.find_element_by_id("login_button").click()
    time.sleep(2)
    driver.refresh()
    # 获取与组合保存cookie
    # 获取cookie列表
    cookie = [item["name"] + ":"+item["value"] for item in driver.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    cookies = {'cookies':cookiestr}
    print cookies
    driver.quit()
    return cookies



if __name__ == '__main__':
    #login_cookies('http://www.yipaiwang.co','17700010001','cq123321')
    login_headers('http://www.yipaiwang.co','17700010001','cq123321')